import configparser
from os import path, makedirs
import requests
import json
import datetime
import argparse
import redis

s = requests.Session()
s.verify = False
url_get_id = "https://app.xiaoyuan.ccb.com/channelManage/outbreak/getMyOutbreak"
url_addoutbreak = 'https://app.xiaoyuan.ccb.com/channelManage/outbreak/addOutbreak'
# redis 配置
redis_host = '127.0.0.1'
redis_port = 6379
redis_db = 0
redis_key = 'access_token'
expire_key = 'expires_in'
redis_conn = None
REDIS_OPEN = True


def read_conf(temp_conf_path):
    with open(temp_conf_path, 'r', encoding='utf-8') as conf_file:
        temp_conf_json = json.load(conf_file)
        return temp_conf_json


def get_args():
    parser = argparse.ArgumentParser(description='Test for argparse')
    parser.add_argument('--conf', '-c', help='用户文件配置文件路径,必要参数', required=True)
    args = parser.parse_args()
    temp_conf_path = args.conf
    return temp_conf_path


def get_now_time():
    now_timeformat = '%Y-%m-%d %H:%M:%S'
    submit_time = datetime.datetime.now().strftime(now_timeformat)
    return submit_time


def get_submit_time():
    ISOTIMEFORMAT = '%Y-%m-%d'
    temp_start_end_time = datetime.datetime.now().strftime(ISOTIMEFORMAT)
    return temp_start_end_time


def get_token(REDIS_OPEN, temp_redis_conn, temp_corpid, temp_corpsecret):
    access_token = None
    if REDIS_OPEN:
        access_token = temp_redis_conn.get(redis_key)
    if not access_token:
        get_token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={temp_corpid}&corpsecret={temp_corpsecret}"
        response = requests.get(get_token_url).text
        response = json.loads(response)
        access_token = response.get(redis_key)
        expires_in = response.get(expire_key)
        # print(access_token)
        if REDIS_OPEN:
            temp_redis_conn.set(redis_key, access_token, nx=True, ex=expires_in)
    if type(access_token) is bytes:
        access_token = str(access_token, encoding="utf-8")
    return access_token


def notify_wechat(text, desp, temp_REDIS_OPEN, temp_redis_conn, temp_corpid, temp_corpsecret):
    access_token = get_token(temp_REDIS_OPEN, temp_redis_conn, temp_corpid, temp_corpsecret)
    if access_token and len(access_token) > 0:
        send_msg_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
        data = {
            "touser": touser,
            "agentid": agentId,
            "msgtype": "textcard",
            "textcard": {
                "title": username + " " + text,
                "description": username + "\n" + desp,
                "url": "https://www.baidu.com",
                "btntxt": "more"
            },
            "duplicate_check_interval": 600
        }
        result = requests.post(send_msg_url, data=json.dumps(data))


def modify_submit_time(temp_conf_json):
    temp_conf_json['data_get_id']['startTime'] = temp_conf_json['data_get_id']['endTime'] = get_submit_time()
    return temp_conf_json


def modify_id(temp_conf_json, temp_id):
    temp_conf_json['data_addoutbreak']['id'] = temp_id
    return temp_conf_json


def get_id(temp_conf_json):
    data_get_id = temp_conf_json['data_get_id']
    data_get_id = json.dumps(data_get_id, ensure_ascii=False)
    headers_get_id = temp_conf_json['headers_get_id']
    result_get_id = s.post(url_get_id, data=data_get_id, headers=headers_get_id)
    return result_get_id.json()['data']['id']


def add_OutBreak(temp_conf_json):
    data_addoutbreak = temp_conf_json['data_addoutbreak']
    nowArea = data_addoutbreak["nowArea"]
    sid = data_addoutbreak["stId"]
    data_addoutbreak = json.dumps(data_addoutbreak, ensure_ascii=False)
    headers_addoutbreak = temp_conf_json['headers_addoutbreak']
    r = s.post(url_addoutbreak, data=data_addoutbreak.encode(), headers=headers_addoutbreak)
    result = r.text
    temp_desp = "提交时间:" + get_now_time() + "\nuser:" + username + "\nsid:" + sid + "\nid:" + id + "\n地点:" + nowArea + "\n结果:" + result + '\n'
    return temp_desp


if REDIS_OPEN:
    try:
        redis_conn = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
        redis_conn.ping()
    except Exception as e:
        REDIS_OPEN = False
        print(e)
        print("--------------未开启redis,不使用redis--------------")
conf_path = get_args()
# conf_path = 'ymy.json'
conf_json = read_conf(conf_path)
add = bool(conf_json['add'])
wechat_conf = conf_json['wechat']
touser = wechat_conf['user_id']
agentId = wechat_conf['app_id']
corpid = wechat_conf['company_id']
corpsecret = wechat_conf['company_secret']
username = conf_json['username']
if not add:
    print(1)
    exit()
conf_json = modify_submit_time(conf_json)
id = get_id(conf_json)
conf_json = modify_id(conf_json, id)
text = "打卡脚本通知"
desp = add_OutBreak(conf_json)
print(desp)
notify_wechat(text, desp, REDIS_OPEN, redis_conn, corpid, corpsecret)
